<template>
  <div class="dashboard">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>数据仪表盘</h1>
      <p>欢迎使用AI伙伴管理后台，这里是系统核心数据概览</p>
    </div>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" :xs="12">
        <div class="data-card">
          <div class="value">{{ formatNumber(stats.totalUsers) }}</div>
          <div class="label">总用户数</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card success">
          <div class="value">{{ formatNumber(stats.vipUsers) }}</div>
          <div class="label">VIP用户</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card warning">
          <div class="value">{{ formatNumber(stats.totalCredits) }}</div>
          <div class="label">积分总消耗</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card info">
          <div class="value">{{ formatNumber(stats.aiImageCount) }}</div>
          <div class="label">AI生图次数</div>
        </div>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-row">
      <!-- 用户增长趋势 -->
      <el-col :span="12">
        <div class="content-card">
          <div class="card-header">
            <h3>用户增长趋势</h3>
            <p>最近30天用户注册情况</p>
          </div>
          <div class="chart-container">
            <v-chart :option="userTrendOption" style="height: 300px;" />
          </div>
        </div>
      </el-col>

      <!-- 积分消耗分布 -->
      <el-col :span="12">
        <div class="content-card">
          <div class="card-header">
            <h3>积分消耗分布</h3>
            <p>各功能积分使用占比</p>
          </div>
          <div class="chart-container">
            <v-chart :option="creditsDistributionOption" style="height: 300px;" />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 最近活动 -->
    <el-row class="activity-row">
      <el-col :span="24">
        <div class="content-card">
          <div class="card-header">
            <h3>最近活动</h3>
            <p>系统最新动态</p>
          </div>
          <el-table :data="recentActivities" style="width: 100%">
            <el-table-column prop="time" label="时间" width="160" />
            <el-table-column prop="user" label="用户" width="120" />
            <el-table-column prop="action" label="操作" width="120" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import VChart from 'vue-echarts'
import { getDashboardStats } from '@/api'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 统计数据
const stats = ref({
  totalUsers: 0,
  vipUsers: 0,
  totalCredits: 0,
  aiImageCount: 0
})

// 最近活动数据
const recentActivities = ref([
  {
    time: '2025-09-19 10:30',
    user: '用户1001',
    action: 'AI生图',
    description: '生成了3张图片',
    status: '成功'
  },
  {
    time: '2025-09-19 10:25',
    user: '用户1002',
    action: '积分充值',
    description: '购买1000积分',
    status: '成功'
  },
  {
    time: '2025-09-19 10:20',
    user: '用户1003',
    action: 'VIP购买',
    description: '购买年度VIP',
    status: '待支付'
  },
  {
    time: '2025-09-19 10:15',
    user: '用户1004',
    action: 'AI生图',
    description: '生成失败，积分已退回',
    status: '失败'
  },
  {
    time: '2025-09-19 10:10',
    user: '用户1005',
    action: '用户注册',
    description: '新用户注册',
    status: '成功'
  }
])

// 用户增长趋势图表配置
const userTrendOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['9-13', '9-14', '9-15', '9-16', '9-17', '9-18', '9-19']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '新增用户',
      type: 'line',
      data: [120, 132, 101, 134, 90, 230, 210],
      smooth: true,
      itemStyle: {
        color: '#409eff'
      },
      areaStyle: {
        color: 'rgba(64, 158, 255, 0.2)'
      }
    },
    {
      name: 'VIP用户',
      type: 'line',
      data: [10, 15, 8, 20, 12, 28, 35],
      smooth: true,
      itemStyle: {
        color: '#67c23a'
      },
      areaStyle: {
        color: 'rgba(103, 194, 58, 0.2)'
      }
    }
  ]
})

// 积分消耗分布图表配置
const creditsDistributionOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '积分消耗',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      data: [
        { value: 1048, name: 'AI生图' },
        { value: 735, name: 'AI视频' },
        { value: 580, name: '高清增强' },
        { value: 484, name: '其他功能' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})

// 格式化数字
const formatNumber = (num: number) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + 'w'
  }
  return num.toLocaleString()
}

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case '成功':
      return 'success'
    case '失败':
      return 'danger'
    case '待支付':
      return 'warning'
    default:
      return ''
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getDashboardStats()
    if (response && response.success) {
      const data = response.data
      stats.value = {
        totalUsers: data.totalUsers || 0,
        vipUsers: data.vipUsers || 0,
        totalCredits: data.totalCredits || 0,
        aiImageCount: data.aiImageCount || 0
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 如果加载失败，使用默认值
    stats.value = {
      totalUsers: 0,
      vipUsers: 0,
      totalCredits: 0,
      aiImageCount: 0
    }
  }
}

// 页面加载
onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.dashboard {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.charts-row {
  margin-bottom: 20px;
}

.activity-row {
  margin-bottom: 20px;
}

.card-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header p {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

.chart-container {
  padding: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-row .el-col {
    margin-bottom: 16px;
  }
  
  .charts-row .el-col {
    margin-bottom: 16px;
  }
}
</style>
